<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>物流管理系统 - 首页</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
    <link rel="stylesheet" href="../css/public.css" media="all">
    <script src="../js/echarts.js"></script>
    <style>
        .layui-card {border:1px solid #f2f2f2;border-radius:5px;}
        .icon {margin-right:10px;color:#1aa094;}
        .icon-cray {color:#ffb800!important;}
        .icon-blue {color:#1e9fff!important;}
        .icon-tip {color:#ff5722!important;}
        .layuimini-qiuck-module {text-align:center;margin-top: 10px}
        .layuimini-qiuck-module a i {display:inline-block;width:100%;height:60px;line-height:60px;text-align:center;border-radius:2px;font-size:30px;background-color:#F8F8F8;color:#333;transition:all .3s;-webkit-transition:all .3s;}
        .layuimini-qiuck-module a cite {position:relative;top:2px;display:block;color:#666;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;font-size:14px;}
        .panel {background-color:#fff;border:1px solid transparent;border-radius:3px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}
        .panel-body {padding:10px}
        .panel-title {margin-top:0;margin-bottom:0;font-size:12px;color:inherit}
        .label {display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em;margin-top: .3em;}
        .chart-container {
            width: 100%;
            height: 300px;
        }
        .dashboard-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #333;
        }
        .dashboard-card {
            margin-bottom: 15px;
        }

        .power-transformer-container {
            display: flex;
            gap: 15px;
            height: 100%;
        }

        .chart-section {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 200px;
            background: #f8f8f8;
            border-radius: 4px;
            padding: 10px;
        }

        .table-section {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .power-table {
            flex: 1;
            overflow-y: auto;
            height: 250px;
        }

        #power-transformer-chart {
            width: 100% !important;
            height: 200px !important;
        }

        #settled-chart, #unsettled-chart {
            width: 100%;
            height: 140px !important;
        }

        .layui-table {
            font-size: 12px;
        }

        .layui-table td, .layui-table th {
            padding: 5px 8px;
            text-align: center;
        }

        .pagination {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-top: 5px;
            gap: 5px;
        }

        .pagination button {
            padding: 3px 8px;
            font-size: 12px;
        }

        .pagination button:hover {
            background: #f5f5f5;
        }

        .pagination button:disabled {
            cursor: not-allowed;
            opacity: 0.6;
        }

        .pagination .current-page {
            padding: 5px 10px;
            background: #1E9FFF;
            color: white;
            border-radius: 3px;
        }

        .layui-card {
            border: 1px solid #f2f2f2;
            border-radius: 5px;
            margin-bottom: 15px;
        }

        .layui-card-header {
            padding: 10px 15px;
            background: #f8f8f8;
            border-bottom: 1px solid #f2f2f2;
            font-weight: bold;
        }

        .layui-card-body {
            padding: 15px;
        }

        .icon {
            margin-right: 10px;
            color: #1aa094;
        }

        .icon-tip {
            color: #ff5722 !important;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <div class="layui-row layui-col-space15">
            <!-- 第一行 -->
            <div class="layui-col-md12">
                <div class="layui-row layui-col-space15">
                    <!-- 当月项目结算 -->
                    <div class="layui-col-md3">
                        <div class="layui-card dashboard-card">
                            <div class="layui-card-header">
                                <i class="fa fa-money icon icon-cray"></i>当月项目结算
                            </div>
                            <div class="layui-card-body" style="display: flex; flex-direction: column; align-items: center;">
                                <div id="settled-chart" style="width: 100%; height: 140px;"></div>
                                <div id="unsettled-chart" style="width: 100%; height: 140px; margin-top: 10px;"></div>
                            </div>
                        </div>
                    </div>

                    <!-- 配变电统计 -->
                    <div class="layui-col-md6">
                        <div class="layui-card">
                            <div class="layui-card-header">
                                <i class="layui-icon layui-icon-lightning icon icon-tip"></i>配变电统计
                            </div>
                            <div class="layui-card-body" style="padding: 10px; height: 250px;">
                                <div class="power-transformer-container" style="height: 100%;">
                                    <!-- 左侧饼图 -->
                                    <div class="chart-section" style="flex: 0.4; min-height: 200px;">
                                        <div id="power-transformer-chart" style="width: 100%; height: 150px;"></div>
                                    </div>

                                    <!-- 右侧表格 -->
                                    <div class="table-section" style="flex: 1;">
                                        <div class="power-table" style="height: 250px; overflow-y: auto;">
                                            <table class="layui-table" style="margin: 0;">
                                                <thead>
                                                <tr>
                                                    <th>序号</th>
                                                    <th>项目名称</th>
                                                    <th>完成状态</th>
                                                    <th>入库状态</th>
                                                    <th>操作</th>
                                                </tr>
                                                </thead>
                                                <tbody id="power-table-body">
                                                <!-- 数据将通过JavaScript动态生成 -->
                                                </tbody>
                                            </table>
                                        </div>
                                        <!-- 分页 -->
                                        <div class="pagination" style="margin-top: 5px;">
                                            <button id="prev-btn">上一页</button>
                                            <span class="current-page" id="current-page">1</span>
                                            <button id="next-btn">下一页</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 计划完成统计 -->
                    <div class="layui-col-md3">
                        <div class="layui-card dashboard-card">
                            <div class="layui-card-header">
                                <i class="fa fa-truck icon icon-cray"></i>计划完成统计
                            </div>
                            <div class="layui-card-body">
                                <div id="transport-chart" class="chart-container"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 第二行 -->
            <div class="layui-col-md12">
                <div class="layui-row layui-col-space15">
                    <!-- 备品统计 -->
                    <div class="layui-col-md3">
                        <div class="layui-card dashboard-card">
                            <div class="layui-card-header">
                                <i class="fa fa-cubes icon icon-blue"></i>备品统计
                                <div style="float: right; margin-top: -5px;">
                                    <input type="text" class="layui-input" id="start-date" placeholder="开始日期" style="display: inline-block; width: 120px; height: 28px; line-height: 28px; font-size: 12px;">
                                    <span style="margin: 0 5px;">至</span>
                                    <input type="text" class="layui-input" id="end-date" placeholder="结束日期" style="display: inline-block; width: 120px; height: 28px; line-height: 28px; font-size: 12px;">
                                </div>
                            </div>
                            <div class="layui-card-body">
                                <div id="spare-parts-chart" class="chart-container" style="height: 300px;"></div>
                            </div>
                        </div>
                    </div>

                    <!-- 新品统计 -->
                    <div class="layui-col-md6">
                        <div class="layui-card dashboard-card">
                            <div class="layui-card-header">
                                <i class="fa fa-cubes icon icon-blue"></i>新品统计
                            </div>
                            <div class="layui-card-body" style="padding: 10px; height: 250px;">
                                <div class="power-transformer-container" style="height: 100%;">
                                    <!-- 左侧饼图 -->
                                    <div class="chart-section" style="flex: 0.4; min-height: 200px;">
                                        <div id="new-product-chart" style="width: 100%; height: 150px;"></div>
                                    </div>

                                    <!-- 右侧表格 -->
                                    <div class="table-section" style="flex: 1;">
                                        <div class="power-table" style="height: 250px; overflow-y: auto;">
                                            <table class="layui-table" style="margin: 0;">
                                                <thead>
                                                <tr>
                                                    <th>序号</th>
                                                    <th>产品名称</th>
                                                    <th>完成状态</th>
                                                    <th>入库状态</th>
                                                    <th>操作</th>
                                                </tr>
                                                </thead>
                                                <tbody id="new-product-table-body">
                                                <!-- 数据将通过JavaScript动态生成 -->
                                                </tbody>
                                            </table>
                                        </div>
                                        <!-- 分页 -->
                                        <div class="pagination" style="margin-top: 5px;">
                                            <button id="new-product-prev-btn">上一页</button>
                                            <span class="current-page" id="new-product-current-page">1</span>
                                            <button id="new-product-next-btn">下一页</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 电缆统计 -->
                    <div class="layui-col-md3">
                        <div class="layui-card dashboard-card">
                            <div class="layui-card-header">
                                <i class="fa fa-bolt icon icon-tip"></i>电缆统计
                            </div>
                            <div class="layui-card-body">
                                <div id="cable-chart" class="chart-container"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 第三行 -->
            <div class="layui-col-md12">
                <div class="layui-row layui-col-space15">
                    <!-- 仓库容积统计 -->
                    <div class="layui-col-md4">
                        <div class="layui-card dashboard-card">
                            <div class="layui-card-header">
                                <i class="fa fa-cubes icon icon-blue"></i>仓库容积统计
                            </div>
                            <div class="layui-card-body">
                                <div id="warehouse-chart" class="chart-container"></div>
                            </div>
                        </div>
                    </div>

                    <!-- 线路统计 -->
                    <div class="layui-col-md4">
                        <div class="layui-card dashboard-card">
                            <div class="layui-card-header">
                                <i class="fa fa-line-chart icon icon-blue"></i>线路统计
                                <div style="float: right; margin-top: -5px;">
                                    <input type="text" class="layui-input" id="line-start-date" placeholder="开始日期" style="display: inline-block; width: 120px; height: 28px; line-height: 28px; font-size: 12px;">
                                    <span style="margin: 0 5px;">至</span>
                                    <input type="text" class="layui-input" id="line-end-date" placeholder="结束日期" style="display: inline-block; width: 120px; height: 28px; line-height: 28px; font-size: 12px;">
                                </div>
                            </div>
                            <div class="layui-card-body">
                                <div id="line-statistics-chart" class="chart-container"></div>
                            </div>
                        </div>
                    </div>

                    <!-- 临措统计 -->
                    <div class="layui-col-md4">
                        <div class="layui-card dashboard-card">
                            <div class="layui-card-header">
                                <i class="fa fa-exchange icon icon-blue"></i>临措统计
                                <div style="float: right; margin-top: -5px;">
                                    <input type="text" class="layui-input" id="temp-start-date" placeholder="开始日期" style="display: inline-block; width: 120px; height: 28px; line-height: 28px; font-size: 12px;">
                                    <span style="margin: 0 5px;">至</span>
                                    <input type="text" class="layui-input" id="temp-end-date" placeholder="结束日期" style="display: inline-block; width: 120px; height: 28px; line-height: 28px; font-size: 12px;">
                                </div>
                            </div>
                            <div class="layui-card-body">
                                <div id="temp-statistics-chart" class="chart-container"></div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

<script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script>
    layui.use(['layer', 'miniTab', 'jquery'], function () {
        var $ = layui.jquery,
            layer = layui.layer,
            miniTab = layui.miniTab;

        miniTab.listen();

        // 配变电统计
        let powerTransformerChart = null;
        let currentPage = 1;
        const pageSize = 4;
        let powerTransformerData = [];
        let totalPages = 0;
        // 初始化配变电项目图表
        function initPowerTransformerChart() {
            // 从后端获取配变电统计数据
            $.ajax({
                url: '/stockOperation/powerTransformerStats',
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    console.log('完整响应:', response);
                    console.log('表格数据:', response.data.tableData);

                    if (response.code === 0 && response.data) {
                        powerTransformerData = response.data.tableData || [];
                        totalPages = Math.ceil(response.data.total / pageSize);

                        const completedCount = response.data.chartData.completedCount || 0;
                        const pendingCount = response.data.chartData.pendingCount || 0;

                        renderPowerTransformerChart(completedCount, pendingCount);
                        renderTable();
                        bindPaginationEvents();
                    } else {
                        console.error('获取配变电统计数据失败:', response.msg);
                        layer.msg('获取配变电统计数据失败: ' + response.msg);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('获取配变电统计数据出错:', error);
                    layer.msg('获取配变电统计数据出错');
                }
            });
        }
        // 渲染配变电图表
        function renderPowerTransformerChart(completedCount, pendingCount) {
            const chartDom = document.getElementById('power-transformer-chart');
            if (!chartDom) {
                console.error('配变电图表容器未找到');
                return;
            }

            if (powerTransformerChart) {
                powerTransformerChart.dispose();
            }

            powerTransformerChart = echarts.init(chartDom);

            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        return params.name + ': ' + params.value + '个项目 (' + params.percent + '%)';
                    }
                },
                series: [{
                    name: '配变电项目',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 5,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        //show: false
                        show: true,  // 显示标签
                        formatter: '{b}: {c} ({d}%)',  // 显示名称、值和百分比
                        color: '#333',  // 文字颜色
                        fontSize: 12,
                        fontWeight: 'bold',
                        position: 'outside'  // 文字显示在饼图外侧
                    },
                    labelLine: {
                        show: true,  // 显示引导线
                        length: 10,  // 第一段线长度
                        length2: 15  // 第二段线长度
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '16',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: [
                        {
                            value: completedCount,
                            name: '已完成',
                            itemStyle: {
                                color: '#FF5722'
                            }
                        },
                        {
                            value: pendingCount,
                            name: '未完成',
                            itemStyle: {
                                color: '#CCCCCC'
                            }
                        }
                    ]
                }]
            };

            powerTransformerChart.setOption(option);
        }
        // 渲染表格
        function renderTable() {
            const tbody = document.getElementById('power-table-body');
            if (!tbody) {
                console.error('表格容器未找到');
                return;
            }

            const start = (currentPage - 1) * pageSize;
            const end = start + pageSize;
            const pageData = powerTransformerData.slice(start, end);

            tbody.innerHTML = pageData.map((item, index) => `
        <tr>
            <td>${start + index + 1}</td>
            <td>${item.name || '--'}</td>
            <td class="${item.completed ? 'status-completed' : 'status-pending'}">
                ${item.completed ? '已完成' : '未完成'}
            </td>
            <td class="${item.inStock ? 'status-in-stock' : 'status-not-in-stock'}">
                ${item.inStock ? '已入库' : '未入库'}
            </td>
            <td>
                <button class="layui-btn layui-btn-xs view-project-btn" data-id="${item.id}">查看</button>
            </td>
        </tr>
    `).join('');

            // 更新分页按钮状态
            const prevBtn = document.getElementById('prev-btn');
            const nextBtn = document.getElementById('next-btn');
            const currentPageSpan = document.getElementById('current-page');

            if (prevBtn) prevBtn.disabled = currentPage === 1;
            if (nextBtn) nextBtn.disabled = currentPage === totalPages;
            if (currentPageSpan) currentPageSpan.textContent = currentPage;
        }
        // 分页功能
        function changePage(direction) {
            const newPage = currentPage + direction;
            if (newPage >= 1 && newPage <= totalPages) {
                currentPage = newPage;
                renderTable();
            }
        }
        // 查看项目详情功能
        function viewProject(id) {
            const project = powerTransformerData.find(item => item.id === id);
            if (project) {
                layer.alert(`查看项目详情：${project.name}<br>完成状态：${project.completed ? '已完成' : '未完成'}<br>入库状态：${project.inStock ? '已入库' : '未入库'}`);
            }
        }
        // 绑定分页按钮事件
        function bindPaginationEvents() {
            const prevBtn = document.getElementById('prev-btn');
            const nextBtn = document.getElementById('next-btn');

            if (prevBtn) prevBtn.addEventListener('click', () => changePage(-1));
            if (nextBtn) nextBtn.addEventListener('click', () => changePage(1));

            // 绑定查看项目按钮事件
            $(document).on('click', '.view-project-btn', function() {
                const id = parseInt($(this).data('id'));
                viewProject(id);
            });
        }





        // 当月项目结算图表
        function initSettlementChart() {
            // 调用后端接口获取数据
            $.ajax({
                url: '/stockOperation/projectCompletionRate',
                type: 'POST',
                dataType: 'json',
                success: function(response) {
                    if (response.code === 0 && response.data) {
                        const data = response.data;
                        const completedRate = data.completedRate || 0;
                        const uncompletedRate = data.uncompletedRate || 0;

                        var settledChart = echarts.init(document.getElementById('settled-chart'));
                        var settledOption = {
                            title: {
                                text: '已完成\n' + completedRate.toFixed(1) + '%',
                                left: 'center',
                                top: 'center',
                                textStyle: {
                                    fontSize: 16,
                                    fontWeight: 'bold',
                                    color: '#FF5722',
                                    lineHeight: 24
                                }
                            },
                            tooltip: {
                                trigger: 'item',
                                formatter: function(params) {
                                    if(params.name === '已完成') {
                                        return '已完成项目: ' + data.completedCount + '个<br/>占比: ' + completedRate.toFixed(1) + '%';
                                    }
                                    return '';
                                }
                            },
                            series: [{
                                name: '已完成',
                                type: 'pie',
                                radius: ['70%', '90%'],
                                avoidLabelOverlap: false,
                                itemStyle: {
                                    color: function(params) {
                                        return params.name === '已完成' ? '#FF5722' : '#CCCCCC';
                                    }
                                },
                                label: {
                                    show: false
                                },
                                emphasis: {
                                    label: {
                                        show: false
                                    }
                                },
                                animationType: 'expansion',
                                animationEasing: 'elasticOut',
                                animationDuration: 1500,
                                data: [{
                                    value: completedRate,
                                    name: '已完成'
                                }, {
                                    value: uncompletedRate,
                                    name: ''
                                }]
                            }]
                        };

                        var unsettledChart = echarts.init(document.getElementById('unsettled-chart'));
                        var unsettledOption = {
                            title: {
                                text: '未完成\n' + uncompletedRate.toFixed(1) + '%',
                                left: 'center',
                                top: 'center',
                                textStyle: {
                                    fontSize: 16,
                                    fontWeight: 'bold',
                                    color: '#5FB878',
                                    lineHeight: 24
                                }
                            },
                            tooltip: {
                                trigger: 'item',
                                formatter: function(params) {
                                    if(params.name === '未完成') {
                                        return '未完成项目: ' + (data.totalCount - data.completedCount) + '个<br/>占比: ' + uncompletedRate.toFixed(1) + '%';
                                    }
                                    return '';
                                }
                            },
                            series: [{
                                name: '未完成',
                                type: 'pie',
                                radius: ['70%', '90%'],
                                avoidLabelOverlap: false,
                                itemStyle: {
                                    color: function(params) {
                                        return params.name === '未完成' ? '#5FB878' : '#CCCCCC';
                                    }
                                },
                                label: {
                                    show: false
                                },
                                emphasis: {
                                    label: {
                                        show: false
                                    }
                                },
                                animationType: 'expansion',
                                animationEasing: 'elasticOut',
                                animationDuration: 1500,
                                animationDelay: 300,
                                data: [{
                                    value: uncompletedRate,
                                    name: '未完成'
                                }, {
                                    value: completedRate,
                                    name: ''
                                }]
                            }]
                        };

                        settledChart.setOption(settledOption);
                        unsettledChart.setOption(unsettledOption);
                    } else {
                        console.error('获取项目完成率失败:', response.msg);
                        layer.msg('获取项目完成率失败: ' + response.msg);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('获取项目完成率出错:', error);
                    layer.msg('获取项目完成率出错');
                }
            });
        }



        // 计划完成情况统计图表
        function initTransportChart() {
            var chart = echarts.init(document.getElementById('transport-chart'));

            // 从后端获取数据
            $.ajax({
                url: '/stockOperation/planCompletionStats',
                type: 'POST',
                dataType: 'json',
                success: function(response) {
                    if (response.code === 0 && response.data) {
                        var data = response.data;
                        var option = {
                            title: {
                                text: '计划完成率',
                                left: 'center'
                            },
                            tooltip: {
                                trigger: 'item',
                                formatter: '{a} <br/>{b}: {c} ({d}%)'
                            },
                            legend: {
                                orient: 'vertical',
                                left: 'left',
                                data: ['已完成', '进行中', '未开始', '已延期']
                            },
                            series: [
                                {
                                    name: '计划状态',
                                    type: 'pie',
                                    radius: ['30%', '70%'],
                                    roseType: 'radius',
                                    label: {
                                        color: '#333'
                                    },
                                    labelLine: {
                                        lineStyle: {
                                            color: 'rgba(0, 0, 0, 0.3)'
                                        },
                                        smooth: 0.2,
                                        length: 10,
                                        length2: 20
                                    },
                                    itemStyle: {
                                        color: function(params) {
                                            var colorList = ['#1E9FFF', '#FFB800', '#FF5722', '#009688'];
                                            return colorList[params.dataIndex];
                                        },
                                        shadowBlur: 200,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    },
                                    data: [
                                        {value: data.completed, name: '已完成', itemStyle: {color: '#009688'}},
                                        {value: data.inProgress, name: '进行中', itemStyle: {color: '#1E9FFF'}},
                                        {value: data.notStarted, name: '未开始', itemStyle: {color: '#FFB800'}},
                                        {value: data.delayed, name: '已延期', itemStyle: {color: '#FF5722'}}
                                    ]
                                }
                            ]
                        };
                        chart.setOption(option);
                    } else {
                        console.error('获取计划完成数据失败:', response.msg);
                        layer.msg('获取计划完成数据失败');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('获取计划完成数据出错:', error);
                    layer.msg('获取计划完成数据出错');
                }
            });

            // 窗口大小变化时重新调整图表大小
            window.addEventListener('resize', function() {
                chart.resize();
            });

            return chart;
        }


        // 备品统计图表
        function initSparePartsChart() {
            var chart = echarts.init(document.getElementById('spare-parts-chart'));

            // 默认加载最近30天数据
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(endDate.getDate() - 30);

            // 初始化日期选择器
            layui.laydate.render({
                elem: '#start-date',
                theme: '#1E9FFF',
                value: formatDate(startDate),
                done: function(value) {
                    loadSparePartsData(value, $('#end-date').val());
                }
            });

            layui.laydate.render({
                elem: '#end-date',
                theme: '#1E9FFF',
                value: formatDate(endDate),
                done: function(value) {
                    loadSparePartsData($('#start-date').val(), value);
                }
            });

            // 初始加载数据
            loadSparePartsData(formatDate(startDate), formatDate(endDate));

            return chart;
        }
        // 加载备品统计数据
        function loadSparePartsData(startDate, endDate) {
            const chart = echarts.getInstanceByDom(document.getElementById('spare-parts-chart'));

            $.ajax({
                url: '/stockOperation/sparePartsStats',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    startTime: startDate,
                    endTime: endDate
                }),
                success: function(response) {
                    if (response.code === 0 && response.data) {
                        const data = response.data;
                        updateSparePartsChart(chart, data);
                    } else {
                        layer.msg('获取备品统计数据失败: ' + response.msg);
                    }
                },
                error: function(xhr, status, error) {
                    layer.msg('获取备品统计数据出错');
                    console.error('获取备品统计数据出错:', error);
                }
            });
        }
        // 更新备品统计图表
        function updateSparePartsChart(chart, data) {
            // 直接使用后端返回的数据
            const categories = data.categories || [];
            const inData = data.inData || [];
            const outData = data.outData || [];

            const option = {
                backgroundColor: "#323a5e",
                tooltip: {
                    trigger: "axis",
                    axisPointer: {
                        type: "shadow"
                    },
                    formatter: function(params) {
                        let result = params[0].name + '<br/>';
                        params.forEach(function(item) {
                            result += item.seriesName + ': ' + item.value + '<br/>';
                        });
                        return result;
                    }
                },
                grid: {
                    left: "2%",
                    right: "4%",
                    bottom: "14%",
                    top: "16%",
                    containLabel: true
                },
                legend: {
                    data: ["入库数量", "出库数量"],
                    right: 10,
                    top: 12,
                    textStyle: {
                        color: "#fff"
                    },
                    itemWidth: 12,
                    itemHeight: 10
                },
                xAxis: {
                    type: "category",
                    data: categories,
                    axisLine: {
                        lineStyle: {
                            color: "white"
                        }
                    },
                    axisLabel: {
                        textStyle: {
                            fontFamily: "Microsoft YaHei",
                            color: "#fff"
                        },
                        rotate: 45, // 旋转标签以防止重叠
                        interval: 0 // 显示所有标签
                    }
                },
                yAxis: {
                    type: "value",
                    axisLine: {
                        show: false,
                        lineStyle: {
                            color: "white"
                        }
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: "rgba(255,255,255,0.3)"
                        }
                    },
                    axisLabel: {
                        color: "#fff"
                    }
                },
                dataZoom: [
                    {
                        show: true,
                        height: 12,
                        xAxisIndex: [0],
                        bottom: "8%",
                        start: 0,
                        end: 100, // 改为100%显示全部
                        handleIcon: "path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z",
                        handleSize: "110%",
                        handleStyle: {
                            color: "#d3dee5"
                        },
                        textStyle: {
                            color: "#fff"
                        },
                        borderColor: "#90979c"
                    },
                    {
                        type: "inside",
                        show: true,
                        start: 0,
                        end: 100
                    }
                ],
                series: [
                    {
                        name: "入库数量",
                        type: "bar",
                        barWidth: "15%",
                        itemStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: "#248ff7" },
                                    { offset: 1, color: "#6851f1" }
                                ]),
                                barBorderRadius: 11
                            }
                        },
                        data: inData
                    },
                    {
                        name: "出库数量",
                        type: "bar",
                        barWidth: "15%",
                        itemStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: "#8bd46e" },
                                    { offset: 1, color: "#09bcb7" }
                                ]),
                                barBorderRadius: 11
                            }
                        },
                        data: outData
                    }
                ]
            };

            chart.setOption(option);
        }
        // 辅助函数：格式化日期为YYYY-MM-DD
        function formatDate(date) {
            const d = new Date(date);
            let month = '' + (d.getMonth() + 1);
            let day = '' + d.getDate();
            const year = d.getFullYear();

            if (month.length < 2) month = '0' + month;
            if (day.length < 2) day = '0' + day;

            return [year, month, day].join('-');
        }


        // 新品统计
        let newProductChart = null;
        let newProductCurrentPage = 1;
        const newProductPageSize = 4;
        let newProductData = [];
        let newProductTotalPages = 0;
        // 初始化新品统计图表
        function initNewProductChart() {
            // 从后端获取新品统计数据
            $.ajax({
                url: '/stockOperation/newProductStats',
                type: 'POST',
                dataType: 'json',
                success: function(response) {
                    if (response.code === 0 && response.data) {
                        newProductData = response.data.tableData || [];
                        newProductTotalPages = Math.ceil(response.data.total / newProductPageSize);

                        const completedCount = response.data.chartData.completedCount || 0;
                        const pendingCount = response.data.chartData.pendingCount || 0;

                        renderNewProductChart(completedCount, pendingCount);
                        renderNewProductTable();
                        bindNewProductPaginationEvents();
                    } else {
                        console.error('获取新品统计数据失败:', response.msg);
                        layer.msg('获取新品统计数据失败: ' + response.msg);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('获取新品统计数据出错:', error);
                    layer.msg('获取新品统计数据出错');
                }
            });
        }
        // 渲染新品图表
        function renderNewProductChart(completedCount, pendingCount) {
            const chartDom = document.getElementById('new-product-chart');
            if (!chartDom) {
                console.error('新品图表容器未找到');
                return;
            }

            if (newProductChart) {
                newProductChart.dispose();
            }

            newProductChart = echarts.init(chartDom);

            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        return params.name + ': ' + params.value + '个产品 (' + params.percent + '%)';
                    }
                },
                series: [{
                    name: '新品统计',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 5,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '16',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: [
                        {
                            value: completedCount,
                            name: '已完成',
                            itemStyle: {
                                color: '#1E9FFF'
                            }
                        },
                        {
                            value: pendingCount,
                            name: '未完成',
                            itemStyle: {
                                color: '#CCCCCC'
                            }
                        }
                    ]
                }]
            };

            newProductChart.setOption(option);
        }
        // 渲染新品表格
        function renderNewProductTable() {
            const tbody = document.getElementById('new-product-table-body');
            if (!tbody) {
                console.error('新品表格容器未找到');
                return;
            }

            const start = (newProductCurrentPage - 1) * newProductPageSize;
            const end = start + newProductPageSize;
            const pageData = newProductData.slice(start, end);

            tbody.innerHTML = pageData.map((item, index) => `
        <tr>
            <td>${start + index + 1}</td>
            <td>${item.name || '--'}</td>
            <td class="${item.completed ? 'status-completed' : 'status-pending'}">
                ${item.completed ? '已完成' : '未完成'}
            </td>
            <td class="${item.inStock ? 'status-in-stock' : 'status-not-in-stock'}">
                ${item.inStock ? '已入库' : '未入库'}
            </td>
            <td>
                <button class="layui-btn layui-btn-xs view-new-product-btn" data-id="${item.id}">查看</button>
            </td>
        </tr>
    `).join('');

            // 更新分页按钮状态
            const prevBtn = document.getElementById('new-product-prev-btn');
            const nextBtn = document.getElementById('new-product-next-btn');
            const currentPageSpan = document.getElementById('new-product-current-page');

            if (prevBtn) prevBtn.disabled = newProductCurrentPage === 1;
            if (nextBtn) nextBtn.disabled = newProductCurrentPage === newProductTotalPages;
            if (currentPageSpan) currentPageSpan.textContent = newProductCurrentPage;
        }
        // 新品分页功能
        function changeNewProductPage(direction) {
            const newPage = newProductCurrentPage + direction;
            if (newPage >= 1 && newPage <= newProductTotalPages) {
                newProductCurrentPage = newPage;
                renderNewProductTable();
            }
        }
        // 查看新品详情功能
        function viewNewProduct(id) {
            const product = newProductData.find(item => item.id === id);
            if (product) {
                layer.alert(`查看产品详情：${product.name}<br>完成状态：${product.completed ? '已完成' : '未完成'}<br>入库状态：${product.inStock ? '已入库' : '未入库'}`);
            }
        }
        // 绑定新品分页按钮事件
        function bindNewProductPaginationEvents() {
            const prevBtn = document.getElementById('new-product-prev-btn');
            const nextBtn = document.getElementById('new-product-next-btn');

            if (prevBtn) prevBtn.addEventListener('click', () => changeNewProductPage(-1));
            if (nextBtn) nextBtn.addEventListener('click', () => changeNewProductPage(1));

            // 绑定查看产品按钮事件
            $(document).on('click', '.view-new-product-btn', function() {
                const id = parseInt($(this).data('id'));
                viewNewProduct(id);
            });
        }



        // 电缆统计图表
        function initCableChart() {
            var chart = echarts.init(document.getElementById('cable-chart'));

            // 从后端获取数据
            $.ajax({
                url: '/stockOperation/cableStats',
                type: 'POST',
                dataType: 'json',
                success: function(response) {
                    if (response.code === 0 && response.data) {
                        var data = response.data;
                        updateCableChart(chart, data);
                    } else {
                        console.error('获取电缆统计数据失败:', response.msg);
                        layer.msg('获取电缆统计数据失败');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('获取电缆统计数据出错:', error);
                    layer.msg('获取电缆统计数据出错');
                }
            });

            // 窗口大小变化时重新调整图表大小
            window.addEventListener('resize', function() {
                chart.resize();
            });

            return chart;
        }
        // 更新电缆统计图表
        function updateCableChart(chart, data) {
            let bgColor = "#fff";
            let title = "总量";
            let color = ["#0E7CE2", "#FF8352", "#E271DE", "#F8456B"];

            // 格式化数据
            let formatNumber = function (num) {
                let reg = /(?=(\B)(\d{3})+$)/g;
                return num.toString().replace(reg, ",");
            };

            let total = (data.copperTotal ? data.copperTotal : 0) + (data.aluminumTotal ? data.aluminumTotal : 0);

            var option = {
                backgroundColor: bgColor,
                color: color,
                title: [
                    {
                        text: "{name|" + title + "}\n{val|" + formatNumber(total) + "}",
                        top: "center",
                        left: "center",
                        textStyle: {
                            rich: {
                                name: {
                                    fontSize: 14,
                                    fontWeight: "normal",
                                    color: "#666666",
                                    padding: [10, 0],
                                },
                                val: {
                                    fontSize: 32,
                                    fontWeight: "bold",
                                    color: "#333333",
                                },
                            },
                        },
                    },
                    {
                        text: "单位：米",
                        top: 2,
                        left: 20,
                        textStyle: {
                            fontSize: 14,
                            color: "#666666",
                            fontWeight: 400,
                        },
                    },
                ],
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        var name = params.name;
                        var value = params.value;
                        var unit = '米';

                        if(name === '同轴电缆收') {
                            return '同轴电缆入库: ' + formatNumber(data.copperIn) + unit;
                        } else if(name === '同轴电缆出') {
                            return '同轴电缆出库: ' + formatNumber(data.copperOut) + unit;
                        } else if(name === '矿用电缆收') {
                            return '矿用电缆入库: ' + formatNumber(data.aluminumIn) + unit;
                        } else if(name === '矿用电缆出') {
                            return '矿用电缆出库: ' + formatNumber(data.aluminumOut) + unit;
                        }
                        return name + ': ' + value + unit;
                    }
                },
                series: [
                    {
                        name: "电缆统计",
                        type: "pie",
                        radius: ["45%", "60%"],
                        center: ["50%", "50%"],
                        data: [
                            {value: data.copperIn, name: '同轴电缆收'},
                            {value: data.copperOut, name: '同轴电缆出'},
                            {value: data.aluminumIn, name: '同轴电缆收'},
                            {value: data.aluminumOut, name: '同轴电缆出'}
                        ],
                        hoverAnimation: true,
                        animationType: 'scale',
                        animationEasing: 'elasticOut',
                        animationDuration: 1000,
                        itemStyle: {
                            normal: {
                                borderColor: bgColor,
                                borderWidth: 2,
                                shadowBlur: 10,
                                shadowColor: 'rgba(0, 0, 0, 0.3)'
                            },
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        labelLine: {
                            normal: {
                                length: 20,
                                length2: 120,
                                lineStyle: {
                                    color: "#e6e6e6",
                                },
                            },
                        },
                        label: {
                            normal: {
                                formatter: (params) => {
                                    return (
                                        "{icon|●}{name|" +
                                        params.name +
                                        "}{value|" +
                                        formatNumber(params.value) +
                                        "}")
                                },
                                padding: [0, -100, 25, -100],
                                rich: {
                                    icon: {
                                        fontSize: 16,
                                    },
                                    name: {
                                        fontSize: 14,
                                        padding: [0, 10, 0, 4],
                                        color: "#666666",
                                    },
                                    value: {
                                        fontSize: 18,
                                        fontWeight: "bold",
                                        color: "#333333",
                                    },
                                },
                            },
                        },
                        emphasis: {
                            scale: true,
                            scaleSize: 10,
                            label: {
                                show: true,
                                fontSize: '18',
                                fontWeight: 'bold'
                            }
                        }
                    },
                ],
            };

            chart.setOption(option);
        }



        // 仓库容积统计图表 - 柱状图
        function initWarehouseChart() {
            var chart = echarts.init(document.getElementById('warehouse-chart'));

            // 从后端获取仓库容量数据
            $.ajax({
                url: '/inventory/warehouseCapacityStats',
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    console.log('完整响应:', response); // 确保这行被执行
                    console.log('响应code:', response.code); // 检查code值
                    console.log('响应data:', response.data); // 检查data内容

                    if (response.code === 0 && response.data) {
                        var data = response.data;

                        // 准备图表数据
                        var categories = [];
                        var usedData = [];
                        var remainingData = [];
                        var usageRateData = [];

                        data.forEach(function(item) {
                            categories.push(item.warehouseName);
                            usedData.push(item.usedCapacity);
                            remainingData.push(item.remainingCapacity);
                            usageRateData.push(parseFloat(item.usageRate));
                        });

                        console.log("完成响应");

                        var option = {
                            title: {
                                text: '仓库容积使用情况',
                                left: 'center',
                                textStyle: {
                                    color: '#333'
                                }
                            },
                            tooltip: {
                                trigger: "axis",
                                axisPointer: {
                                    type: "shadow"
                                },
                                formatter: function(params) {
                                    var result = params[0].name + '<br/>';
                                    params.forEach(function(item) {
                                        var value = item.value;
                                        if (item.seriesName === '使用率') {
                                            value = value + '%';
                                        } else {
                                            value = value + 'm³';
                                        }
                                        result += item.marker + ' ' + item.seriesName + ': ' + value + '<br/>';
                                    });
                                    return result;
                                }
                            },
                            legend: {
                                data: ["已使用", "剩余", "使用率"],
                                right: 10,
                                top: 10,
                                textStyle: {
                                    color: '#666'
                                }
                            },
                            grid: {
                                left: "3%",
                                right: "4%",
                                bottom: "14%",
                                top: "16%",
                                containLabel: true
                            },
                            xAxis: {
                                type: "category",
                                data: categories,
                                axisLine: {
                                    lineStyle: {
                                        color: "#666"
                                    }
                                },
                                axisLabel: {
                                    color: "#666",
                                    rotate: 30 // 旋转标签防止重叠
                                }
                            },
                            yAxis: [
                                {
                                    type: "value",
                                    name: "容积(m³)",
                                    axisLine: {
                                        lineStyle: {
                                            color: "#666"
                                        }
                                    },
                                    splitLine: {
                                        show: true,
                                        lineStyle: {
                                            color: "rgba(0,0,0,0.1)"
                                        }
                                    },
                                    axisLabel: {
                                        color: "#666",
                                        formatter: '{value}'
                                    }
                                },
                                {
                                    type: "value",
                                    name: "使用率(%)",
                                    min: 0,
                                    max: 100,
                                    axisLine: {
                                        lineStyle: {
                                            color: "#666"
                                        }
                                    },
                                    splitLine: {
                                        show: false
                                    },
                                    axisLabel: {
                                        color: "#666",
                                        formatter: '{value}%'
                                    }
                                }
                            ],
                            series: [
                                {
                                    name: "已使用",
                                    type: "bar",
                                    barWidth: "20%",
                                    itemStyle: {
                                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                            { offset: 0, color: "#248ff7" },
                                            { offset: 1, color: "#6851f1" }
                                        ]),
                                        barBorderRadius: [4, 4, 0, 0]
                                    },
                                    label: {
                                        show: true,
                                        position: 'top',
                                        formatter: '{c}m³'
                                    },
                                    data: usedData
                                },
                                {
                                    name: "剩余",
                                    type: "bar",
                                    barWidth: "20%",
                                    itemStyle: {
                                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                            { offset: 0, color: "#8bd46e" },
                                            { offset: 1, color: "#09bcb7" }
                                        ]),
                                        barBorderRadius: [0, 0, 4, 4]
                                    },
                                    label: {
                                        show: true,
                                        position: 'top',
                                        formatter: '{c}m³'
                                    },
                                    data: remainingData
                                },
                                {
                                    name: "使用率",
                                    type: "line",
                                    yAxisIndex: 1,
                                    symbolSize: 8,
                                    itemStyle: {
                                        color: "#FF5722"
                                    },
                                    label: {
                                        show: true,
                                        formatter: '{c}%'
                                    },
                                    data: usageRateData
                                }
                            ]
                        };

                        chart.setOption(option);
                    } else {
                        console.error('获取仓库容量数据失败:', response.msg);
                        // 显示错误信息
                        chart.setOption({
                            title: {
                                text: '数据加载失败',
                                left: 'center',
                                top: 'center',
                                textStyle: {
                                    color: '#FF5722',
                                    fontSize: 16
                                }
                            }
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('获取仓库容量数据出错:', error);
                    // 显示错误信息
                    chart.setOption({
                        title: {
                            text: '数据加载出错',
                            left: 'center',
                            top: 'center',
                            textStyle: {
                                color: '#FF5722',
                                fontSize: 16
                            }
                        }
                    });
                }
            });

            // 窗口大小变化时重新调整图表大小
            window.addEventListener('resize', function() {
                chart.resize();
            });

            return chart;
        }



        //计划管理：需要每个计划和相对应的计划数量和实际入库数量
        // 线路统计图表
        function initLineStatisticsChart() {
            var chart = echarts.init(document.getElementById('line-statistics-chart'));

            // 初始化日期选择器
            layui.laydate.render({
                elem: '#line-start-date',
                theme: '#1E9FFF',
                done: function(value) {
                    loadLineStatsData(value, $('#line-end-date').val());
                }
            });

            layui.laydate.render({
                elem: '#line-end-date',
                theme: '#1E9FFF',
                done: function(value) {
                    loadLineStatsData($('#line-start-date').val(), value);
                }
            });

            // 初始加载数据
            loadLineStatsData('', '');

            return chart;
        }
        // 加载线路统计数据
        function loadLineStatsData(startDate, endDate) {
            const chart = echarts.getInstanceByDom(document.getElementById('line-statistics-chart'));

            $.ajax({
                url: '/stockOperation/lineStats',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    startTime: startDate,
                    endTime: endDate
                }),
                success: function(response) {
                    if (response.code === 0 && response.data) {
                        updateLineStatsChart(chart, response.data);
                    } else {
                        layer.msg('获取线路统计数据失败: ' + response.msg);
                    }
                },
                error: function(xhr, status, error) {
                    layer.msg('获取线路统计数据出错');
                    console.error('获取线路统计数据出错:', error);
                }
            });
        }
        // 更新线路统计图表
        function updateLineStatsChart(chart, data) {
            // 准备图表数据
            const categories = data.map(item => item.projectName);
            const plannedData = data.map(item => item.plannedQuantity);
            const inData = data.map(item => item.inQuantity);
            const completionRates = data.map(item => item.completionRate);

            const option = {
                backgroundColor: "#fff",
                title: {
                    text: '线路统计',
                    left: 'center',
                    textStyle: {
                        color: '#333',
                        fontSize: 16
                    }
                },
                tooltip: {
                    trigger: "axis",
                    axisPointer: {
                        type: "shadow"
                    },
                    formatter: function(params) {
                        let result = params[0].name + '<br/>';
                        params.forEach(function(item) {
                            result += item.marker + ' ' + item.seriesName + ': ' + item.value + '米<br/>';
                        });
                        // 添加完成率
                        const index = params[0].dataIndex;
                        result += '完成率: ' + completionRates[index] + '%';
                        return result;
                    }
                },
                legend: {
                    data: ["计划数量", "入库数量"],
                    right: 10,
                    top: 10,
                    textStyle: {
                        color: "#666"
                    }
                },
                grid: {
                    left: "3%",
                    right: "4%",
                    bottom: "14%",
                    top: "20%",
                    containLabel: true
                },
                xAxis: {
                    type: "category",
                    data: categories,
                    axisLine: {
                        lineStyle: {
                            color: "#666"
                        }
                    },
                    axisLabel: {
                        color: "#666",
                        interval: 0,
                        rotate: 30
                    }
                },
                yAxis: {
                    type: "value",
                    name: "数量(米)",
                    axisLine: {
                        show: false,
                        lineStyle: {
                            color: "#666"
                        }
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: "rgba(0,0,0,0.1)"
                        }
                    },
                    axisLabel: {
                        color: "#666",
                        formatter: '{value}'
                    }
                },
                dataZoom: [
                    {
                        show: true,
                        height: 12,
                        xAxisIndex: [0],
                        bottom: "8%",
                        start: 0,
                        end: 100,
                        handleIcon: "path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z",
                        handleSize: "110%",
                        handleStyle: {
                            color: "#d3dee5"
                        },
                        textStyle: {
                            color: "#666"
                        },
                        borderColor: "#90979c"
                    },
                    {
                        type: "inside",
                        show: true,
                        start: 0,
                        end: 100
                    }
                ],
                series: [
                    {
                        name: "计划数量",
                        type: "bar",
                        barWidth: "15%",
                        itemStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: "#248ff7" },
                                    { offset: 1, color: "#6851f1" }
                                ]),
                                barBorderRadius: 4
                            }
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}米'
                        },
                        data: plannedData
                    },
                    {
                        name: "入库数量",
                        type: "bar",
                        barWidth: "15%",
                        itemStyle: {
                            normal: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: "#8bd46e" },
                                    { offset: 1, color: "#09bcb7" }
                                ]),
                                barBorderRadius: 4
                            }
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: function(params) {
                                const rate = completionRates[params.dataIndex];
                                return params.value + '米 (' + rate + '%)';
                            }
                        },
                        data: inData
                    }
                ]
            };

            chart.setOption(option);

            // 窗口大小变化时重新调整图表大小
            window.addEventListener('resize', function() {
                chart.resize();
            });
        }


        // 临措统计图表
        // function initTempStatisticsChart() {
        //     var chart = echarts.init(document.getElementById('temp-statistics-chart'));
        //
        //     // 模拟数据 - 临措统计
        //     var categories = ['电缆A', '变压器B', '开关C', '电表D', '绝缘子E', '断路器F', '避雷器G', '电容器H'];
        //     var outData = [1200, 800, 1500, 900, 600, 400, 300, 200]; // 出库数量
        //     var inData = [1000, 750, 1300, 850, 550, 380, 280, 180]; // 入库数量
        //
        //     var option = {
        //         backgroundColor: "#fff",
        //         tooltip: {
        //             trigger: "axis",
        //             axisPointer: {
        //                 type: "shadow"
        //             },
        //             formatter: function(params) {
        //                 var result = params[0].name + '<br/>';
        //                 params.forEach(function(item) {
        //                     result += item.marker + ' ' + item.seriesName + ': ' + item.value + '个<br/>';
        //                 });
        //                 // 添加完成率计算
        //                 if(params.length > 1) {
        //                     var completionRate = (params[1].value / params[0].value * 100).toFixed(1);
        //                     result += '完成率: ' + completionRate + '%';
        //                 }
        //                 return result;
        //             }
        //         },
        //         legend: {
        //             data: ["出库数量", "入库数量"],
        //             right: 10,
        //             top: 10,
        //             textStyle: {
        //                 color: "#666"
        //             }
        //         },
        //         grid: {
        //             left: "3%",
        //             right: "4%",
        //             bottom: "14%",
        //             top: "16%",
        //             containLabel: true
        //         },
        //         xAxis: {
        //             type: "category",
        //             data: categories,
        //             axisLine: {
        //                 lineStyle: {
        //                     color: "#666"
        //                 }
        //             },
        //             axisLabel: {
        //                 color: "#666",
        //                 interval: 0,
        //                 rotate: 30
        //             }
        //         },
        //         yAxis: {
        //             type: "value",
        //             axisLine: {
        //                 show: false,
        //                 lineStyle: {
        //                     color: "#666"
        //                 }
        //             },
        //             splitLine: {
        //                 show: true,
        //                 lineStyle: {
        //                     color: "rgba(0,0,0,0.1)"
        //                 }
        //             },
        //             axisLabel: {
        //                 color: "#666",
        //                 formatter: '{value}'
        //             }
        //         },
        //         dataZoom: [
        //             {
        //                 show: true,
        //                 height: 12,
        //                 xAxisIndex: [0],
        //                 bottom: "8%",
        //                 start: 0,
        //                 end: 50,
        //                 handleIcon: "path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z",
        //                 handleSize: "110%",
        //                 handleStyle: {
        //                     color: "#d3dee5"
        //                 },
        //                 textStyle: {
        //                     color: "#666"
        //                 },
        //                 borderColor: "#90979c"
        //             },
        //             {
        //                 type: "inside",
        //                 show: true,
        //                 start: 0,
        //                 end: 50
        //             }
        //         ],
        //         series: [
        //             {
        //                 name: "出库数量",
        //                 type: "bar",
        //                 barWidth: "15%",
        //                 itemStyle: {
        //                     normal: {
        //                         color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        //                             { offset: 0, color: "#FF5722" },
        //                             { offset: 1, color: "#FFB800" }
        //                         ]),
        //                         barBorderRadius: 4
        //                     }
        //                 },
        //                 data: outData
        //             },
        //             {
        //                 name: "入库数量",
        //                 type: "bar",
        //                 barWidth: "15%",
        //                 itemStyle: {
        //                     normal: {
        //                         color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        //                             { offset: 0, color: "#1E9FFF" },
        //                             { offset: 1, color: "#009688" }
        //                         ]),
        //                         barBorderRadius: 4
        //                     }
        //                 },
        //                 data: inData
        //             }
        //         ]
        //     };
        //
        //     chart.setOption(option);
        //
        //     // 初始化日期选择器
        //     layui.laydate.render({
        //         elem: '#temp-start-date',
        //         theme: '#1E9FFF',
        //         done: function(value) {
        //             console.log('开始日期:', value);
        //             // 这里可以添加数据重新加载的逻辑
        //         }
        //     });
        //     layui.laydate.render({
        //         elem: '#temp-end-date',
        //         theme: '#1E9FFF',
        //         done: function(value) {
        //             console.log('结束日期:', value);
        //             // 这里可以添加数据重新加载的逻辑
        //         }
        //     });
        //
        //     // 自动轮播高亮效果
        //     var app = { currentIndex: -1 };
        //     setInterval(function () {
        //         var dataLen = option.series[0].data.length;
        //         chart.dispatchAction({
        //             type: "downplay",
        //             seriesIndex: 0,
        //             dataIndex: app.currentIndex
        //         });
        //         app.currentIndex = (app.currentIndex + 1) % dataLen;
        //         chart.dispatchAction({
        //             type: "highlight",
        //             seriesIndex: 0,
        //             dataIndex: app.currentIndex
        //         });
        //         chart.dispatchAction({
        //             type: "showTip",
        //             seriesIndex: 0,
        //             dataIndex: app.currentIndex
        //         });
        //     }, 2000);
        //
        //     window.addEventListener('resize', function() {
        //         chart.resize();
        //     });
        //
        //     return chart;
        // }


        // 临措统计图表
        function initTempStatisticsChart() {
            var chart = echarts.init(document.getElementById('temp-statistics-chart'));

            // 从后端获取数据
            function loadTempStatsData(startDate, endDate) {
                $.ajax({
                    url: '/stockOperation/temporaryMeasureStats',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        startTime: startDate,
                        endTime: endDate
                    }),
                    success: function(response) {
                        if (response.code === 0 && response.data) {
                            updateTempStatsChart(chart, response.data);
                        } else {
                            layer.msg('获取临措统计数据失败: ' + response.msg);
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.msg('获取临措统计数据出错');
                        console.error('获取临措统计数据出错:', error);
                    }
                });
            }

            // 更新图表
            function updateTempStatsChart(chart, data) {
                var names = data.names || [];
                var inQuantities = data.inQuantities || [];
                var outQuantities = data.outQuantities || [];
                var completionRates = data.completionRates || [];

                var option = {
                    backgroundColor: "#fff",
                    tooltip: {
                        trigger: "axis",
                        axisPointer: {
                            type: "shadow"
                        },
                        formatter: function(params) {
                            var result = params[0].name + '<br/>';
                            params.forEach(function(item) {
                                result += item.marker + ' ' + item.seriesName + ': ' + item.value + '个<br/>';
                            });
                            // 添加完成率
                            var index = params[0].dataIndex;
                            if (completionRates[index]) {
                                result += '完成率: ' + completionRates[index];
                            }
                            return result;
                        }
                    },
                    legend: {
                        data: ["出库数量", "入库数量"],
                        right: 10,
                        top: 10,
                        textStyle: {
                            color: "#666"
                        }
                    },
                    grid: {
                        left: "3%",
                        right: "4%",
                        bottom: "14%",
                        top: "16%",
                        containLabel: true
                    },
                    xAxis: {
                        type: "category",
                        data: names,
                        axisLine: {
                            lineStyle: {
                                color: "#666"
                            }
                        },
                        axisLabel: {
                            color: "#666",
                            interval: 0,
                            rotate: 30
                        }
                    },
                    yAxis: {
                        type: "value",
                        axisLine: {
                            show: false,
                            lineStyle: {
                                color: "#666"
                            }
                        },
                        splitLine: {
                            show: true,
                            lineStyle: {
                                color: "rgba(0,0,0,0.1)"
                            }
                        },
                        axisLabel: {
                            color: "#666",
                            formatter: '{value}'
                        }
                    },
                    dataZoom: [
                        {
                            show: true,
                            height: 12,
                            xAxisIndex: [0],
                            bottom: "8%",
                            start: 0,
                            end: 50,
                            handleIcon: "path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z",
                            handleSize: "110%",
                            handleStyle: {
                                color: "#d3dee5"
                            },
                            textStyle: {
                                color: "#666"
                            },
                            borderColor: "#90979c"
                        },
                        {
                            type: "inside",
                            show: true,
                            start: 0,
                            end: 50
                        }
                    ],
                    series: [
                        {
                            name: "出库数量",
                            type: "bar",
                            barWidth: "15%",
                            itemStyle: {
                                normal: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: "#FF5722" },
                                        { offset: 1, color: "#FFB800" }
                                    ]),
                                    barBorderRadius: 4
                                }
                            },
                            data: outQuantities
                        },
                        {
                            name: "入库数量",
                            type: "bar",
                            barWidth: "15%",
                            itemStyle: {
                                normal: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: "#1E9FFF" },
                                        { offset: 1, color: "#009688" }
                                    ]),
                                    barBorderRadius: 4
                                }
                            },
                            data: inQuantities
                        }
                    ]
                };

                chart.setOption(option);
            }

            // 初始化日期选择器
            layui.laydate.render({
                elem: '#temp-start-date',
                theme: '#1E9FFF',
                done: function(value) {
                    loadTempStatsData(value, $('#temp-end-date').val());
                }
            });

            layui.laydate.render({
                elem: '#temp-end-date',
                theme: '#1E9FFF',
                done: function(value) {
                    loadTempStatsData($('#temp-start-date').val(), value);
                }
            });

            // 初始加载数据
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(endDate.getDate() - 30);
            loadTempStatsData(formatDate(startDate), formatDate(endDate));

            // 窗口大小变化时重新调整图表大小
            window.addEventListener('resize', function() {
                chart.resize();
            });

            return chart;
        }


        // 初始化所有图表
        function initAllCharts() {
            setTimeout(function() {
                // 当月项目结算图表
                initSettlementChart();

                //配变电统计
                initPowerTransformerChart();
                renderTable();
                bindPaginationEvents();

                // 计划完成统计
                initTransportChart();
                // 备品统计图表
                initSparePartsChart();

                // 新品统计初始化
                initNewProductChart();
                renderNewProductTable();
                bindNewProductPaginationEvents();


                // 电缆统计
                initCableChart();

                // 仓库容积统计
                initWarehouseChart()

                // 线路统计
                initLineStatisticsChart()

                // 临措统计
                initTempStatisticsChart();
            }, 100);
        }

        // 窗口大小变化时重新调整图表大小
        window.onresize = function(){
            if (powerTransformerChart) {
                powerTransformerChart.resize();
            }
            initAllCharts();
        };

        // 初始化所有图表
        initAllCharts();
    });
</script>
</body>
</html>
